﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Swork03_28.Api.Application.Commands.UserCommand;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Swork03_28.Api.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginsController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IMediator mediator;

        public LoginsController(IConfiguration configuration, IMediator mediator)
        {
            this.configuration = configuration;
            this.mediator = mediator;
        }

        

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromQuery] UserCommand command)
        {
            var info = await mediator.Send(command);
            if (info != null)
            {
                var token = JwtNewString(info.UserId.ToString());
                info.Token = token;
                return Ok(info);
            }
            return null;
        }

        private string JwtNewString(string uid)
        {
            //选择算法
            var signingAlorithm = SecurityAlgorithms.HmacSha256;
            //payLoad存放用户信息
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes .Role,"admin"),
                new Claim(ClaimTypes.UserData,"2024-04-09")
            };
            //取出私钥并以utf8编码输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);

            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);

            //使用hmacsha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlorithm);

            //生成token
            var Token = new JwtSecurityToken(
                    issuer: configuration["Authentication:Issuer"],         //发布者
                    audience: configuration["Authentication:Audience"],     //接收者
                    claims: claims,                                         //存放的用户信息
                    notBefore: DateTime.Now,                                //发布时间
                    expires: DateTime.Now.AddDays(1),                       //有效期为1天
                    signingCredentials                                      //数字签名
                );

            //生成字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);

            return TokenStr;

        }
    }


}
